﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Threading;
using LiSAClient.Core.Viewmodel;

namespace LiSAClient.WpfClient.ViewModel.Frame.Menus
{
    internal class MenuViewModel : ContentViewModel
    {
        public ObservableCollection<MenuItemBase> MenuItems { get; private set; }

        private MenuItemBase selectedMenuItem;

        public MenuItemBase SelectedMenuItem
        {
            get
            {
                return this.selectedMenuItem;
            }

            set
            {
                this.Set(() => this.SelectedMenuItem, ref this.selectedMenuItem, value);
                if (value != null)
                {
                    value.ActivateMenuAction();

                    // If the part should not be marked as the selected:
                    if (!value.IsSelectable)
                    {
                        this.SelectedMenuItem = null;
                    }
                }
            }
        }

        internal MenuViewModel()
        {
            this.MenuItems = new ObservableCollection<MenuItemBase>();
        }

        public void Fill(List<MenuItemBase> menuItems)
        {
            this.Fill(menuItems, null);
        }

        public void Fill(List<MenuItemBase> menuItems, MenuItemBase selMenuItem)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
            {
                this.MenuItems.Clear();
                foreach (var menuItemBase in menuItems)
                {
                    this.MenuItems.Add(menuItemBase);
                    menuItemBase.ChildActivatedEvent += this.MenuItemBaseOnChildActivatedEvent;
                }

                this.SelectedMenuItem = selMenuItem;
            });
        }

        public void FillNoAction(List<MenuItemBase> menuItems, MenuItemBase selMenuItem)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
            {
                this.MenuItems.Clear();
                foreach (var menuItemBase in menuItems)
                {
                    this.MenuItems.Add(menuItemBase);
                    menuItemBase.ChildActivatedEvent += this.MenuItemBaseOnChildActivatedEvent;
                }

                DispatcherHelper.CheckBeginInvokeOnUI(() => this.Set(() => this.SelectedMenuItem, ref this.selectedMenuItem, selMenuItem));
            });
        }

        private void MenuItemBaseOnChildActivatedEvent(object sender, EventArgs eventArgs)
        {
            var selMenuItem = sender as MenuItemBase;
            if (selMenuItem == null)
            {
                return;
            }

            DispatcherHelper.CheckBeginInvokeOnUI(() => this.Set(() => this.SelectedMenuItem, ref this.selectedMenuItem, selMenuItem));
        }
    }
}
